package cn.tedu.webapi.order.service.impl;
import cn.tedu.dubbo.service.CartService;
import cn.tedu.micro.service.pojo.param.OrderAddParam;
import cn.tedu.micro.service.pojo.po.OrderPO;
import cn.tedu.service.order.service.OrderService;
import cn.tedu.webapi.order.mapper.OrderMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

//@Service
@DubboService
public class OrderServiceImpl  implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @DubboReference //表明要发现对应的服务信息
    private CartService cartService;

    @Override
    public Boolean addOrder(OrderAddParam orderAddParam) {
        //新增订单入库之前-减少库存(是否充足)-删除购物车(对应用户的对应商品)
        //1.减少库存数
       // stockClient.reduceStock(orderAddParam.getProductCode(),orderAddParam.getCount());
        //2.删除购物中的商品
        cartService.deleteCart(orderAddParam.getProductCode(),orderAddParam.getUserId());
        //cartClient.deleteCart(orderAddParam.getProductCode(),orderAddParam.getUserId());
        //3.新增订单到数据库中
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderAddParam,orderPO);
        orderPO.setOrderSn((new Date()).toString());
        int orderResult = orderMapper.insert(orderPO);
        //为了验证分布式事务效果，随机抛出异常
        if(Math.random()<0.6){
            System.out.println(1/0);
        }
        if(!(orderResult>=1))
            return false;
        return true;
    }
}
